//
//  WLSystemMsgVController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/17.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLSystemMsgVController.h"
#import "WLMsgModel.h"
#import "WLMessageDetailController.h"
#import "WLWebViewController.h"
#import "WLMessageCell.h"

@interface WLSystemMsgVController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tbSysMsg;
@property (nonatomic, strong) NSMutableArray    *arrSysMsgs;
@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation WLSystemMsgVController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kHasReadedMessageNofication object:nil];
}
- (void)refreshUI {
    [self.tbSysMsg reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"系统公告";
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshUI) name:kHasReadedMessageNofication object:nil];
    _arrSysMsgs = [[NSMutableArray alloc] init];
    _pageNum = 1;
    
    _tbSysMsg = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tbSysMsg.delegate = self;
    _tbSysMsg.dataSource = self;
    _tbSysMsg.rowHeight  = WLScaleX(70);
//    _tbSysMsg.separatorColor = HPBoardColor;
//    _tbSysMsg.backgroundColor = HPLightLineColor;
    if (@available(iOS 11.0, *)) {
        _tbSysMsg.estimatedSectionHeaderHeight = 0;
        _tbSysMsg.estimatedSectionFooterHeight = 0;
    }
    _tbSysMsg.tableFooterView = [UIView new];
    [self.view addSubview:_tbSysMsg];
    WLWkSelf
    [_tbSysMsg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
    _tbSysMsg.mj_header = [WLFreshGifHeader headerWithRefreshingBlock:^{
        weakSelf.tbSysMsg.mj_footer = nil;
        [weakSelf.arrSysMsgs removeAllObjects];
        weakSelf.pageNum = 1;
        [weakSelf reqSystemMsg];
    }];
    
    [self reqSystemMsg];
}

- (void)addMsgFooterRefresh
{
    WLWkSelf
    _tbSysMsg.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf reqSystemMsg];
    }];
}

- (void)reqSystemMsg
{
    WLWkSelf
    NSDictionary *params = @{@"page":@(_pageNum),@"num":@10};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"noticemsg/system/user" withParamsDic:params success:^(NSDictionary *successDict) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.tbSysMsg.mj_header endRefreshing];
        NSInteger productCount = [successDict[@"count"] integerValue];
        if (strongSelf.pageNum==1&&productCount>10)
        {
            [strongSelf addMsgFooterRefresh];
        }
        NSArray *arrPros = [WLMsgModel mj_objectArrayWithKeyValuesArray:successDict[@"object"]];
        if (arrPros.count>0) {
            [strongSelf.arrSysMsgs addObjectsFromArray:arrPros];
            if (strongSelf.arrSysMsgs.count >= productCount) {
                [strongSelf.tbSysMsg.mj_footer endRefreshingWithNoMoreData];
            }
            else
            {
                [strongSelf.tbSysMsg.mj_footer endRefreshing];
            }
            [strongSelf.tbSysMsg reloadData];
        }
        else
        {
            [strongSelf.tbSysMsg.mj_footer endRefreshingWithNoMoreData];
        }
        strongSelf.pageNum += 1;
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
        [weakSelf.tbSysMsg.mj_header endRefreshing];
        [weakSelf.tbSysMsg.mj_footer endRefreshing];
    } error:^(NSError *error) {
        [weakSelf.tbSysMsg.mj_header endRefreshing];
        [weakSelf.tbSysMsg.mj_footer endRefreshing];
    } inView:(_pageNum==1&&_tbSysMsg.mj_header.isRefreshing==NO)?self.view:nil];
}

#pragma mark - UITableView
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//    return _arrSysMsgs.count;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return WLScaleX(20);
}

//- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
//{
//    return 0.01;
//}

//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    WLMsgModel *msgModel = self.arrSysMsgs[section];
//    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH_SCREEN_WL, WLScaleX(40))];
////    headerView.backgroundColor = [UIColor whiteColor];
//    UILabel *labTime = [[UILabel alloc] initWithFrame:CGRectMake(WLScaleX(20), WLScaleX(10), WIDTH_SCREEN_WL-WLScaleX(40), WLScaleX(30))];
//    labTime.textAlignment = NSTextAlignmentCenter;
//    labTime.font = [WLCommonTool fontTypePingFangSCRegular:12];
//    labTime.textColor = wlLightTextColor;
//    labTime.text = [WLCommonTool timeIntervalDescription:msgModel.noticeTime];
//    [headerView addSubview:labTime];
//    return headerView;
//}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _arrSysMsgs.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strSysMsg = @"systemMsgCell";
    WLMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:strSysMsg];
    if (!cell) {
        cell = [[WLMessageCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strSysMsg];
    }
    
    WLMsgModel *msgModel = self.arrSysMsgs[indexPath.row];
    cell.btnHead.backgroundColor = wlUIColorRGB(0x29A8FA);
    [cell.btnHead setImage:[UIImage imageNamed:@"msg_system"] forState:UIControlStateNormal];
    cell.labTitle.text = msgModel.title;
    cell.labDetail.text = msgModel.content;
    cell.labDetail.textColor = wlLightTextColor;
    if (msgModel.url.length>5) {
        cell.labDetail.text = @"打开链接";
        cell.labDetail.textColor = wlUIColorRGB(0xFFBA20);
        cell.ivLink.hidden = NO;
    }
    else
    {
        cell.labDetail.text = msgModel.content;
        cell.ivLink.hidden = YES;
    }
    
    cell.labTime.text = [WLCommonTool timeIntervalDescription:msgModel.noticeTime];
    if (msgModel.hasLook==1)
    {
        cell.vUnread.hidden = YES;
    }
    else
    {
        cell.vUnread.hidden = NO;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WLMsgModel *model = self.arrSysMsgs[indexPath.row];
    if (model.url.length>7)
    {
        WLWebViewController *webView = [[WLWebViewController alloc] init];
        webView.urlStr = model.url;
        webView.titleStr = model.title;
        webView.msgId = model.msgId;
        model.hasLook = 1;
        [self.navigationController pushViewController:webView animated:YES];
    }
    else
    {
        WLMessageDetailController *msgDetailController = [[WLMessageDetailController alloc] init];
        msgDetailController.messageInfo = model;
        [self.navigationController pushViewController:msgDetailController animated:YES];
        model.hasLook = 1;
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
